package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"math/rand"
	"mxshop_srvs/inventory_srv/proto"
	"sync"
	"time"
)

var invClient proto.InventoryClient
var conn *grpc.ClientConn

/*
*
测试库存
*/
func main() {
	Init()
	//设置库存
	//TestSetInv()
	//获取库存详情
	//TestInvDetail()

	//扣减库存
	/*var wg sync.WaitGroup
	wg.Add(10)
	for i := 0; i < 10; i++ {
		num := rand.Int63n(100)
		time.Sleep(time.Millisecond * 100)
		OrderSn := GenerateOrderSn(int32(num))
		go TestSell(&wg, OrderSn)
	}
	wg.Wait()
	fmt.Println("all is done")*/

	//测试归还库存
	TestReBack()
}

// 测试设置库存
func TestSetInv() {
	_, err := invClient.SetInv(context.Background(), &proto.GoodsInvInfo{
		GoodsId: 423,
		Num:     100,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("设置库存成功")
}

// 测试扣减库存
func TestSell(wg *sync.WaitGroup, OrderSn string) {
	defer wg.Done()
	invClient.Sell(context.Background(), &proto.SellInfo{
		GoodsInfo: []*proto.GoodsInvInfo{
			{GoodsId: 421, Num: 1},
			{GoodsId: 422, Num: 1},
		},
		OrderSn: OrderSn,
	})
	fmt.Println("扣减库存成功")
}

// 获取库存详情
func TestInvDetail() {
	detail, err := invClient.InvDetail(context.Background(), &proto.GoodsInvInfo{
		GoodsId: 421,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(detail)
}

/*
*
测试归还库存
*/
func TestReBack() {
	invClient.Reback(context.Background(), &proto.SellInfo{
		GoodsInfo: []*proto.GoodsInvInfo{
			{GoodsId: 421, Num: 10},
			{GoodsId: 422, Num: 10},
		},
	})
}

func Init() {
	var err error
	conn, err = grpc.Dial("192.168.31.78:50053", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	invClient = proto.NewInventoryClient(conn)
}

func GenerateOrderSn(userId int32) string {
	//订单号的生成规则
	/*
		年月日时分秒+用户id+2位随机数
	*/
	now := time.Now()
	rand.Seed(time.Now().UnixNano())
	orderSn := fmt.Sprintf("%d%d%d%d%d%d%d%d",
		now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Nanosecond(),
		userId, rand.Intn(90)+10,
	)
	return orderSn
}
